home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / docs / mags / AIOV55.lha / AIOIssue55 / examples / 2.6_evenodd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1980-01-01  |  1.9 KB  |  33 lines

  1. #include <stdio.h>
  2.  
  3. int main(void)
  4. {
  5.   int i = 0;
  6.   int even_array[100];    /* create an array with the compiler */
  7.   int * odd_array = NULL; /* int pointer for a "hand-made" array */
  8.   int * odd_array_alias = NULL; /* will be modifying odd_array pointer, but still have to free() the original address. Remember original address with odd_array_alias */
  9.  
  10.   odd_array = (int *) calloc(100, sizeof(int) ); /* alloc mem for the "hand-made" pointer, 100 elements */
  11.   odd_array_alias = odd_array;                   /* remember the original calloc()'d address with odd_array_alias */
  12.   if (odd_array) /* error checking */
  13.   {
  14.     odd_array[0] = 1;  /* make first element the first odd number, 1 */
  15.     even_array[0] = 2; /* make first element the first even number, 2 */
  16.     for (i = 1; i <= 99; i++) /* loop 99 times (element 0 for both arrays are done), fill arrays */
  17.     {
  18.       odd_array[i] = odd_array[i - 1] + 2; /* fill odd array with odd numbers. This line shows a "hand-made" array can be used like a "compiler" one. */
  19.       even_array[i] = even_array[i -1] + 2; /* fill even array with even numbers */
  20.     }
  21.     for (i = 0; i <= 99; i++) /* loop 100 times, display array contents */
  22.     {
  23.       printf("\n#:%i. Odd: %i. Even: %i.", i, *odd_array, even_array[i]);
  24.       odd_array++; /* Move pointer to next element. Can't do this with even_array since it's a "fixed" pointer */
  25.     }
  26.     printf("\n\nFirst elements again: Odd: %i Even %i.\n", *odd_array_alias, *even_array); /* This line shows you can still dereference a "fixed" pointer in a "compiler" array */
  27.     free(odd_array_alias); /* Can't use odd_array, since odd_array doesn't point to originally calloc'd address anymore. */
  28.   } /* NB: In your own programming, try to use pointer aliases when you want to modifiable pointer, so you can use the same pointer used for calloc() with free() */
  29.   else printf("\nMemory alloc failed.\n"); /* if odd_array failed on alloc */
  30.  
  31.   return 0;
  32. }
  33.